package com.example.design.patterns.geekbang.行为型.解释器模式.自定义接口告警;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 案例
 * 命令：api_error_per_minute > 100 || api_count_per_minute > 10000
 * 描述：每分钟 API 总出错数超过 100 或者每分钟 API 总调用数超过 10000 就触发告警。
 */
public interface Expression {
    boolean interpret(Map<String, Long> stats);
}

// LessExpression/EqualExpression跟GreaterExpression代码类似，这里就省略了

public class AndExpression implements Expression {
    private List<Expression> expressions = new ArrayList<>();

    public AndExpression(String strAndExpression) {
        String[] strExpressions = strAndExpression.split("&&");
        for (String strExpr : strExpressions) {
            if (strExpr.contains(">")) {
                expressions.add(new GreaterExpression(strExpr));
            } else if (strExpr.contains("<")) {
                expressions.add(new LessExpression(strExpr));
            } else if (strExpr.contains("==")) {
                expressions.add(new EqualExpression(strExpr));
            } else {
                throw new RuntimeException("Expression is invalid: " + strAndExpression);
            }
        }
    }

    public AndExpression(List<Expression> expressions) {
        this.expressions.addAll(expressions);
    }

    @Override
    public boolean interpret(Map<String, Long> stats) {
        for (Expression expr : expressions) {
            if (!expr.interpret(stats)) {
                return false;
            }
        }
        return true;
    }

}

